package com.leoman.service.impl;

import com.leoman.controller.common.CommonController;
import com.leoman.core.Constant;
import com.leoman.dao.*;
import com.leoman.entity.*;
import com.leoman.exception.MoneyShortException;
import com.leoman.exception.NoDataException;
import com.leoman.exception.ParamErrorException;
import com.leoman.service.PaperService;
import com.leoman.utils.DateUtils;
import com.leoman.utils.JsonUtil;
import com.leoman.utils.QiNiuUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * PaperServiceImpl
 * Created by 涂奕恒 on 2016/11/23 0023 下午 4:00.
 */
@Service
public class PaperServiceImpl implements PaperService {

    @Autowired
    private PaperDao paperDao;

    @Autowired
    private CommentDao commentDao;

    @Autowired
    private ImageDao imageDao;

    @Autowired
    private PraiseDao praiseDao;

    @Autowired
    private UserCollectDao userCollectDao;

    @Autowired
    private LetterAnnexSampleDao letterAnnexSampleDao;

    @Autowired
    private PaperImageDao paperImageDao;

    @Autowired
    private UserBuyRecordDao userBuyRecordDao;

    @Autowired
    private UserDao userDao;

    @Override
    public List<Paper> findAll() {
        return paperDao.findAll();
    }

    @Override
    public Page<Paper> find(int pageNum, int pageSize) {
        return paperDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
    }

    @Override
    public Page<Paper> find(int pageNum) {
        return find(pageNum, Constant.PAGE_DEF_SIZE);
    }

    @Override
    public Paper getById(int id) {
        return paperDao.findOne(id);
    }

    @Override
    @Transactional
    public void deleteById(int id) {
        List<String> tempUrl = new ArrayList<>();
        List<Image> imageList;

        // 删除该纸条的所有评论
        List<Comment> commentList = commentDao.findListBySourceIdAndType(id, Constant.SOURCE_TYPE_PAPER);
        for (Comment comment : commentList) {
            // 删除评论中的图片
            imageList = imageDao.findListByParams(comment.getId(), Constant.SOURCE_TYPE_COMMENT);
            for (Image image : imageList) {
                tempUrl.add(image.getUrl());
                imageDao.delete(image);
            }

            // 删除评论中的语音文件
            if (comment.getVoiceTime() > 0) {
                tempUrl.add(comment.getContent());
            }

            commentDao.delete(comment.getId());
        }

        // 删除该纸条的所有收藏
        List<UserCollect> collectList = userCollectDao.findListBySourceIdAndType(id, Constant.SOURCE_TYPE_PAPER);
        for (UserCollect userCollect : collectList) {
            userCollectDao.delete(userCollect);
        }

        // 删除该纸条的所有点赞
        List<Praise> praiseList = praiseDao.findListBySourceIdAndType(id, Constant.SOURCE_TYPE_PAPER);
        for (Praise praise : praiseList) {
            praiseDao.delete(praise);
        }

        // 删除该纸条的所有图片
        imageList = imageDao.findListByParams(id, Constant.SOURCE_TYPE_PAPER);
        for (Image image : imageList) {
            tempUrl.add(image.getUrl());
            imageDao.delete(image);
        }

        paperDao.delete(id);

        for (String url : tempUrl) {
            QiNiuUtils.delete(url);
        }
    }

    @Override
    public Paper create(Paper paper) {
        return paperDao.save(paper);
    }

    @Override
    public Paper update(Paper paper) {
        return paperDao.save(paper);
    }

    @Override
    @Transactional
    public void deleteAll(int[] ids) {
        for (int id : ids) {
            deleteById(id);
        }
    }

    @Override
    public Page<Paper> iPageForApp(final Integer userId, final Integer isMe, Integer pageNum, Integer pageSize) {
        Integer[] info = CommonController.getPageParams(pageNum, pageSize);

        Page<Paper> page = paperDao.findAll(new Specification<Paper>() {
            @SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
            @Override
            public Predicate toPredicate(Root<Paper> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate result = null;
                List<Predicate> predicateList = new ArrayList<>();

                if (null != userId && null != isMe && isMe.equals(Constant.USER_STATUS_YES)) {
                    predicateList.add(cb.equal(root.get("user").get("id").as(Integer.class), userId));
                } else {
                    predicateList.add(cb.equal(root.get("isDraft").as(Integer.class), Constant.USER_STATUS_NO));

                    predicateList.add(cb.equal(root.get("moneyStatus").as(Integer.class), Constant.GIVE_MONEY_STATUS_YES));
                }

                if (predicateList.size() > 0) {
                    result = cb.and(predicateList.toArray(new Predicate[]{}));
                }

                if (result != null) {
                    query.where(result);
                }
                return query.getGroupRestriction();
            }

        }, new PageRequest(info[0] - 1, info[1], Sort.Direction.DESC, "isAdmin", "isTop", "id"));

        for (Paper paper : page.getContent()) {
            changePaperInfo(paper, null == isMe || isMe.equals(Constant.USER_STATUS_NO) ? userId : null);
        }

        return page;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Page<Paper> iPageForAppCollect(Integer userId, Integer pageNum, Integer pageSize) {
        Integer[] info = CommonController.getPageParams(pageNum, pageSize);
        PageRequest pageRequest = new PageRequest(info[0] - 1, info[1], Sort.Direction.DESC, "id");

        final Page<UserCollect> userCollectPage = userCollectDao.iPageByUserId(userId, Constant.SOURCE_TYPE_PAPER, pageRequest);

        List<Paper> list = new ArrayList<>();
        for (UserCollect userCollect : userCollectPage.getContent()) {
            list.add(paperDao.findOne(userCollect.getSourceId()));
        }

        Page<Paper> paperPage2 = new PageImpl(list, pageRequest, userCollectPage.getTotalElements());

        for (Paper paper : paperPage2.getContent()) {
            changePaperInfo(paper, userId);
        }

        return paperPage2;
    }

    @Override
    @Transactional
    public Integer addPaperInfo(Boolean isAdmin, Integer userId, Integer tempId, Integer paperId, Integer type, String content, Integer isDraft) throws ParamErrorException {
        if (null == userId || null == type || StringUtils.isBlank(content) || null == isDraft) {
            throw new ParamErrorException();
        }

        PaperImage paperImage = paperImageDao.findOne(paperId);

        if (null == paperImage) {
            throw new ParamErrorException();
        }

        User user = new User();
        user.setId(userId);

        Paper paper;

        if (null == tempId) {
            paper = new Paper();
        } else {
            paper = paperDao.findOne(tempId);
        }

        paper.setUser(user);
        paper.setPaperId(paperId);
        paper.setNum(paperImage.getNum());
        paper.setType(type);
        paper.setContent(content);
        paper.setIsAdmin(isAdmin ? Constant.USER_STATUS_YES : Constant.USER_STATUS_NO);
        paper.setIsDraft(isDraft);

        if (type != 2 && paperImage.getMoney() <= 0) {
            paper.setMoneyStatus(Constant.USER_STATUS_YES);
        }

        if (isDraft.equals(Constant.USER_STATUS_YES)) {
            Paper tempPaper = paperDao.iFindDraftByUserId(userId);
            deleteById(tempPaper.getId());
        }

        paperDao.save(paper);

        if (isDraft.equals(Constant.USER_STATUS_NO)) {
            // 保存购买记录
            UserBuyRecord userBuyRecord = new UserBuyRecord();

            userBuyRecord.setUser(user);
            userBuyRecord.setSourceId(paper.getId());
            userBuyRecord.setSourceType(3);
            userBuyRecord.setNum(paperImage.getNum());
            userBuyRecord.setMoney(paperImage.getMoney());

            userBuyRecordDao.save(userBuyRecord);
        }

        return paper.getId();
    }

    @Override
    public Paper iFindDraftByUserId(Integer userId) throws ParamErrorException, NoDataException {
        return paperDao.iFindDraftByUserId(userId);
    }

    @Override
    public Page<Paper> pageByParams(final String userName, final String startTime, final String endTime, final Integer type, final String num, Integer pageNum, Integer pageSize) {
        return paperDao.findAll(new Specification<Paper>() {
            @SuppressWarnings("ToArrayCallWithZeroLengthArrayArgument")
            @Override
            public Predicate toPredicate(Root<Paper> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate result = null;
                List<Predicate> predicateList = new ArrayList<>();

                if (StringUtils.isNotBlank(userName)) {
                    predicateList.add(cb.like(root.get("user").get("nickName").as(String.class), "%" + userName + "%"));
                }

                if (StringUtils.isNotBlank(startTime)) {
                    try {
                        System.out.println("");
                        Long startDate = DateUtils.stringToDateWithFormat(startTime, "yyyy-MM-dd hh:mm:ss").getTime();
                        predicateList.add(cb.gt(root.get("createTime").as(Long.class), startDate));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                if (StringUtils.isNotBlank(endTime)) {
                    try {
                        System.out.println("");
                        Long endDate = DateUtils.stringToDateWithFormat(endTime, "yyyy-MM-dd hh:mm:ss").getTime();
                        predicateList.add(cb.lt(root.get("createTime").as(Long.class), endDate));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

                if (null != type) {
                    predicateList.add(cb.equal(root.get("type").as(Integer.class), type));
                }

                if (StringUtils.isNotBlank(num)) {
                    predicateList.add(cb.like(root.get("num").as(String.class), "%" + num + "%"));
                }

                predicateList.add(cb.equal(root.get("isDraft").as(Integer.class), Constant.USER_STATUS_NO));

                if (predicateList.size() > 0) {
                    result = cb.and(predicateList.toArray(new Predicate[]{}));
                }

                if (result != null) {
                    query.where(result);
                }
                return query.getGroupRestriction();
            }

        }, new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "isAdmin", "isTop", "id"));
    }

    @Override
    @Transactional
    public Integer toTop(Integer paperId) {
        try {
            Paper topPaper = paperDao.iFindOneWithTop();
            Paper paper = paperDao.findOne(paperId);

            if (null != topPaper && paperId.equals(topPaper.getId())) {
                return -1;
            }

            if (null != topPaper) {
                topPaper.setIsTop(Constant.USER_STATUS_NO);
                paperDao.save(topPaper);
            }

            paper.setIsTop(Constant.USER_STATUS_YES);
            paperDao.save(paper);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    @Transactional
    public Integer batchDelete(String ids) {
        try {
            Integer[] paperIds = JsonUtil.json2Obj(ids, Integer[].class);

            for (Integer paperId : paperIds) {
                deleteById(paperId);
            }

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    @Transactional
    public Integer savePaper(String content, Integer type, Integer paperId) {
        try {
            Paper paperByAdmin = paperDao.iFindOneWithAdmin();

            if (null != paperByAdmin) {
                deleteById(paperByAdmin.getId());
            }

            LetterAnnexSample letterAnnexSample = letterAnnexSampleDao.findOneByLetterAnnexId(paperId);

            paperByAdmin = new Paper();
            paperByAdmin.setPaperId(paperId);
            paperByAdmin.setNum(letterAnnexSample.getNum());
            paperByAdmin.setType(type);
            paperByAdmin.setContent(content);
            paperByAdmin.setIsAdmin(Constant.USER_STATUS_YES);

            paperDao.save(paperByAdmin);

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public void changeMoneyStatus(Integer id) {
        Paper paper = paperDao.findOne(id);

        if (null != paper && paper.getIsDraft().equals(Constant.USER_STATUS_NO)) {
            paper.setMoneyStatus(Constant.USER_STATUS_YES);
            paperDao.save(paper);
        }
    }

    @Override
    public void changeMoneyStatusByMoney(Integer id, Double money) throws ParamErrorException, MoneyShortException {
        Paper paper = paperDao.findOne(id);
        User user;

        if (null != paper && paper.getIsDraft().equals(Constant.USER_STATUS_NO)) {
            // 修改用户账户余额
            user = paper.getUser();

            if (null == user) {
                throw new ParamErrorException();
            }
            System.out.println();
            if (user.getMoney() < money) {
                throw new MoneyShortException();
            }

            user.setMoney(user.getMoney() - money);
            userDao.save(user);

            paper.setMoneyStatus(Constant.USER_STATUS_YES);
            paperDao.save(paper);
        } else {
            throw new ParamErrorException();
        }
    }

    /**
     * 加载纸条附属信息
     *
     * @param paper  纸条信息
     * @param userId 用户ID
     */
    private void changePaperInfo(Paper paper, Integer userId) {
        if (null == userId) {
            paper.setIsPraise(Constant.USER_STATUS_NO);
            paper.setIsCollect(Constant.USER_STATUS_NO);
        } else {
            paper.setIsPraise(null == praiseDao.findOneByParams(userId, paper.getId(), Constant.SOURCE_TYPE_PAPER) ? Constant.USER_STATUS_NO : Constant.USER_STATUS_YES);
            paper.setIsCollect(null == userCollectDao.findOneByParams(userId, paper.getId(), Constant.SOURCE_TYPE_PAPER) ? Constant.USER_STATUS_NO : Constant.USER_STATUS_YES);
        }

        Integer praiseNum = praiseDao.findListBySourceIdAndType(paper.getId(), Constant.SOURCE_TYPE_PAPER).size();
        Integer commentNum = commentDao.findListBySourceIdAndType(paper.getId(), Constant.SOURCE_TYPE_PAPER).size();

        paper.setPraiseNum(praiseNum * 2 + commentNum);
        paper.setCommentNum(commentNum);
        paper.setCollectNum(userCollectDao.findListBySourceIdAndType(paper.getId(), Constant.SOURCE_TYPE_PAPER).size());
        paper.setBackgroundImage(letterAnnexSampleDao.findOneByLetterAnnexId(paper.getPaperId()).getCover());
        paper.setContent(paper.getContent().replaceAll("&lt", "<").replaceAll("&gt", ">"));

        if (paper.getIsAdmin().equals(Constant.USER_STATUS_NO)) {
            // 不是管理员
            paper.setUserId(paper.getUser().getId());
            paper.setRegionInfo(null != paper.getUser().getRegion() ? paper.getUser().getRegion().getCity().getProvince().getName() + "|" + paper.getUser().getRegion().getCity().getName() : "");
            paper.setAvatar(paper.getUser().getAvatar());
            paper.setNickName(paper.getUser().getNickName());
        }
    }
}